import {
  Component, OnInit, OnChanges, OnDestroy, AfterViewInit,
  Input, Output, EventEmitter, ElementRef, SimpleChanges
} from '@angular/core';

import * as Cropper from 'cropperjs';

@Component({
  selector: 'app-my-cropper',
  templateUrl: './my.cropper.component.html',
  styleUrls: ['./my.cropper.component.css']
})
export class MyCropperComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy {

  @Input() newImageUrl: String;

  @Input() aspectRatio: number = 1 / 1;

  @Output() okButton = new EventEmitter();

  private cropper;

  constructor(private element: ElementRef) {
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    // TODO 此处可能是版本有问题，会有错误 2017-10-11
    // this.cropper.destroy();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.cropper != null) {
      this.cropper.replace(this.newImageUrl, false);
    }
  }

  ngAfterViewInit(): void {
    this.cropper = new Cropper(this.element.nativeElement.querySelector('#cropper'), {
      aspectRatio: this.aspectRatio
    });
  }

  cropImage() {
    let canvas = this.cropper.getCroppedCanvas();
    if (!canvas) {
      return;
    }
    this.okButton.emit(canvas.toDataURL('image/jpeg'));
  }

}
